<template>
  <div class="third-order">
    <el-form class="third-form" inline :model="orderData.search" ref="searchRef" label-width="100px" @submit.prevent @keypress.enter="onSearchClick">
      <el-form-item label="订单编号">
        <el-input class="third_input" v-model="orderData.search.orderCode" placeholder="请选择订单编号" clearable></el-input>
      </el-form-item>
      <el-form-item label="下单时间">
        <el-date-picker class="date_input" v-model="orderData.search.createTime" type="daterange" format="YYYY/MM/DD" value-format="YYYY/MM/DD" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" @change="onTimeChange" clearable></el-date-picker>
      </el-form-item>
      <el-form-item label="采购商">
        <el-select v-model="orderData.search.customerId" filterable placeholder="请选择采购商" clearable>
          <el-option v-for="item in orderData.customerList" :label="item.customerName" :value="item.customerId" :key="item.customerId"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item class="button-item">
        <Button label="重置" @click="onResetFormClick" />
        <Button label="搜索" type="primary" @click="onSearchClick" />
      </el-form-item>
    </el-form>

    <div class="outerTable">
      <div v-if="route.path === '/order'">
        <Button label="批量取消订单" @click="onBatchClick" :disabled="orderData.selected.length === 0" />

        <el-dropdown>
          <Button label="批量导出订单" type="primary" :disabled="orderData.selected.length === 0" />
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="onSelEcportClick">导出选中订单</el-dropdown-item>
              <el-dropdown-item @click="onSearchExportClick">导出搜索订单</el-dropdown-item>
              <el-dropdown-item @click="onAllExportClick">导出全部订单</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>

        <div v-if="route.path === '/payment'">
          <el-tabs v-model="activeName" @tab-click="onTabClick" type="card">
            <el-tab-pane label="待审核" name="PAYAUDIT" />
            <el-tab-pane label="已通过" name="PASS" />
            <el-tab-pane label="已驳回" name="PAYREJECT" />
          </el-tabs>
          <div v-if="activeName === 'PAYAUDIT'">
            <Button label="通过" type="primary" @click="onPassClick" :disabled="orderData.selected.length === 0" />
            <Button label="驳回" @click="onRejectClick" :disabled="orderData.selected.length === 0" />
          </div>
        </div>
      </div>

      <el-table ref="tableRef" :data="orderData.list" :height="tableHeight" @selection-change="onSelectionChange" v-loading="loading" @filter-change="onFilterChange">
        <el-table-column type="selection" width="50" v-if="route.path === '/order' || route.path === '/payment'" />
        <el-table-column prop="orderCode" width="200" label="订单编号" />
        <el-table-column prop="createTime" width="200" label="下单时间" />
        <el-table-column prop="orderPrice" label="订单金额/元" />
        <el-table-column prop="orderReceivePrice" label="折扣金额/元"/>
        <el-table-column prop="memberName" label="会员等级" />
        <el-table-column prop="customerName" label="采购商" />
        <el-table-column
          prop="settleType"
          label="支付方式"
          column-key="settleType"
          :filter-multiple="false"
          :filters="
            Object.keys(consts.settleType).map((key) => {
              return { text: consts.settleType[key], value: key }
            })
          "
        >
          <template #default="scope">
            <span>{{ consts.settleType[scope.row.settleType] }}</span>
          </template>
        </el-table-column>
        <el-table-column
          v-if="route.path === '/order'"
          prop="orderStatus"
          label="订单状态"
          column-key="orderStatus"
          :filter-multiple="false"
          :filters="
            Object.keys(consts.orderStatus).map((key) => {
              return { text: consts.orderStatus[key], value: key }
            })
          "
        >
          <template #default="scope">
            <span>{{ consts.orderStatus[scope.row.orderStatus] }}</span>
            <span class="after-sale" v-if="scope.row.afterSaleFlag === 'APPLY' || scope.row.afterSaleFlag === 'AFTERSALEING'">售后中</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="afterSaleFlag"
          label="售后状态"
          v-if="route.meta.ori === 'afterSale'"
          :formatter="(row, column, cellValue, index) => $formater.formaterAfterSaleFlag(cellValue)"
          column-key="afterSaleFlag"
          :filter-multiple="false"
          :filters="
            Object.keys(consts.afterSaleFlag).map((key) => {
              return { text: consts.afterSaleFlag[key], value: key }
            })
          "
        />

        <div v-if="route.path === '/payment'">
          <el-table-column prop="paySuccTime" width="200" label="支付时间" />
          <el-table-column prop="payProof" width="200" label="支付凭证" />
        </div>
        <el-table-column v-if="route.path === '/afterSale'" prop="type" label="售后类型">
          <template #default>
            <span v-text="orderData.text" />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="110">
          <template #default="scope">
            <template v-if="route.path === '/payment' && orderData.search.status === 'PAYAUDIT'">
              <Link label="审核" @click="onAuditDetailClick(scope.row.orderId)" />
            </template>

            <Link v-else label="详情" @click="onToDetailClick(scope.row.orderId)" />

            <Link label="售后" v-if="route.path === '/afterSale'" @click="onToAfterSaleClick(scope.row.orderId)" />

            <template v-if="route.path === '/deliver'">
              <span v-if="scope.row.afterSaleFlag === 'APPLY' || scope.row.afterSaleFlag === 'AFTERSALEING'" class="after-sale-deliver">售后中</span>
              <Link label="发货" v-else @click="onDeliverClick(scope.row)" :underline="false" />
            </template>
          </template>
        </el-table-column>
      </el-table>
      <Pager :page="orderData.search.page" :pageSizes="orderData.search.pageSizes" :total="orderData.total" :limit="orderData.search.limit" @current-change="onCurrentChange" @size-change="onSizeChange" />
    </div>
  </div>
  <Track v-model:visible="trackingVisible" @change="onTrackChange" />
  <Reject v-model:visible="rejectVisible" @change="onRejectChange" />
  <Remark v-model:visible="remarkVisible" @change="onRemarkChange" />
</template>
<script setup>
import { reactive, onMounted, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { calcTableHeight } from '@/assets/js/utils.js'
import api from '@/api'
import consts from '@/consts'
import Pager from '@/components/pager/index.vue'
import Track from '@/components/track/index.vue'
import Reject from '@/components/reject/index.vue'
import Remark from '@/components/remark/index.vue'
import Button from '@/components/button/button.vue'
import Link from '@/components/button/link.vue'

const { tableRef, tableHeight } = calcTableHeight()
const router = useRouter()
const route = useRoute()

const orderData = reactive({
  total: 0,
  list: [],
  customerList: [],
  search: {
    page: 1,
    limit: consts.Limit,
    pageSizes: consts.PageSize,
    orderCode: '',
    customerId: '',
    createTime: '',
    createTimeBegin: '',
    createTimeEnd: '',
    status: 'PAYAUDIT',
    orderStatus: '',
    goodsType: ''
  },
  selected: [],
  row: {},
  trackingNumber: '',
  text: '退货退款',
  rejectedForm: {}
})
const loading = ref(false)
const activeName = ref('PAYAUDIT')
const trackingVisible = ref(false)
const rejectVisible = ref(false)
const remarkVisible = ref(false)

watch(
  () => route.meta.ori,
  (val) => {
    if (val) {
      loadData()
    }
  }
)

const cancelOrders = async (orderIds, remark) => {
  let { err } = await api.post(`/medinstrument/third/order/batchCancelOrder?orderIds=${orderIds}&&remark=${remark}`)
  if (err) {
    ElMessage.error(err)
  } else {
    ElMessage.success('订单批量取消成功')
    loadData()
  }
}

const deliver = async (row) => {
  let { err } = await api.post(`/medinstrument/third/order/deliver?orderId=${row.orderId}&&trackingNumber=${orderData.trackingNumber}`)
  if (err) {
    ElMessage.error(err)
  } else {
    ElMessage.success('订单发货成功')
    loadData()
  }
}

const audit = async (operateType, orderIds, remark) => {
  let { err } = await api.post(`/medinstrument/third/order/auditOrderPay?remark=${remark}&orderIds=${orderIds}&operateType=${operateType}`)
  if (err) {
    ElMessage.error(err)
  } else {
    operateType === 'REJECT' ? ElMessage.success('订单已驳回') : ElMessage.success('订单通过审核')
    loadData()
  }
}

const customerData = async () => {
  let { data, err } = await api.get('/medinstrument/third/order/getCustomerList')
  if (err) {
    ElMessage.error(err)
  } else {
    orderData.customerList = data.customerVos
  }
}

const loadData = async () => {
  loading.value = true
  if (orderData.search.createTime) {
    orderData.search.createTimeBegin = orderData.search.createTime[0]
    orderData.search.createTimeEnd = orderData.search.createTime[1]
  }
  let url = '/medinstrument/third/order/getOrderList'

  let params = Object.assign({}, orderData.search)
  delete params.createTime
  if (route.meta.ori === 'pay') {
    if (orderData.search.status === 'PASS') {
      url = `/medinstrument/third/order/getOrderList?orderPayStatus=true`
    } else {
      params.orderStatus = orderData.search.status
    }
    delete params.status
    delete params.afterSaleFlag
  } else if (route.meta.ori === 'afterSale') {
    url = '/medinstrument/third/order/getOrderList?backOrderFlag=YES'
    params.orderStatus = ''
    delete params.status
  } else if (route.meta.ori === 'deliver') {
    params.orderStatus = 'UNDELIVER'
    delete params.status
    delete params.afterSaleFlag
  } else if (route.meta.ori === 'list') {
    delete params.status
    delete params.afterSaleFlag
  }

  let { data, err } = await api.get(url, params)
  loading.value = false
  if (err) {
    ElMessage.error(err)
  } else {
    orderData.list = data.list
    orderData.total = data.count
  }
}

const onResetFormClick = () => {
  orderData.search = {}
  loadData()
}

const onSelectionChange = (val) => {
  orderData.selected = val
}

const onBatchClick = () => {
  remarkVisible.value = true
}

const onSelEcportClick = () => {
  let orderIds = orderData.selected.map((e) => e.orderId).join(',')
  if (!orderIds) {
    ElMessage.warning('请选择订单')
  }
  api.download(`/medinstrument/third/exportExcel/exportCheckOrder?orderIds=${orderIds}`)
}

const onSearchExportClick = () => {
  let orderIds = orderData.selected.map((e) => e.orderId).join(',')
  // let params = Object.assign({}, orderData.search)
  let params = JSON.parse(JSON.stringify(orderData.search))
  // if ((!params.createTime || !params.customerId || !params.supplierId || !params.orderCode) && !orderIds) {
  //   ElMessage.warning('请搜索订单并选择订单')
  //   return
  // }
  delete params.createTime
  delete params.status
  delete params.pageSizes

  api.download('/medinstrument/third/exportExcel/exportOrder', params)
}

const onAllExportClick = () => {
  // if (orderData.selected.length !== orderData.list.length) {
  //   ElMessage.warning('请全选订单')
  //   return
  // }
  api.download('/medinstrument/third/exportExcel/exportOrder')
}

const onToDetailClick = (orderId) => {
  let { href } = router.resolve({
    path: `/order/detail/${orderId}`
  })
  window.open(href, '_blank')
}
const onAuditDetailClick = (orderId) => {
  let { href } = router.resolve({
    path: `/order/audit/${orderId}`
  })
  window.open(href, '_blank')
}

const onToAfterSaleClick = (orderId) => {
  let { href } = router.resolve({
    path: `/afterSale/detail/${orderId}`
  })
  window.open(href, '_blank')
}

const onCurrentChange = (val) => {
  orderData.search.page = val
  loadData()
}

const onSizeChange = (val) => {
  orderData.search.limit = val
  loadData()
}

const onSearchClick = () => {
  orderData.search.page = 1
  loadData()
}

const onTimeChange = (val) => {
  if (val) {
    orderData.search.createTimeBegin = val[0]
    orderData.search.createTimeEnd = val[1]
  } else {
    orderData.search.createTimeBegin = ''
    orderData.search.createTimeEnd = ''
  }
}

const onTabClick = (tab) => {
  orderData.search.status = tab.props.name
  loadData()
}

const onDeliverClick = (row) => {
  orderData.row = Object.assign({}, row)
  trackingVisible.value = true
}

const onTrackChange = (val) => {
  orderData.trackingNumber = val
  deliver(orderData.row)
}

const onRemarkChange = (val) => {
  let orderIds = orderData.selected.map((e) => e.orderId).join(',')

  cancelOrders(orderIds, val)
}

const onPassClick = () => {
  if (orderData.selected.length === 0) {
    ElMessage.error('请选择订单')
    return
  }
  let orderIds = orderData.selected.map((e) => e.orderId).join(',')
  audit('PASS', orderIds, ' ')
}

const onRejectClick = () => {
  if (orderData.selected.length === 0) {
    ElMessage.error('请选择订单')
    return
  }
  rejectVisible.value = true
}

const onRejectChange = (val) => {
  let orderIds = orderData.selected.map((e) => e.orderId).join(',')
  audit('REJECT', orderIds, val)
}

const onFilterChange = (filters) => {
  Object.keys(filters).forEach((e) => {
    orderData.search[e] = filters[e]
  })
  loadData()
}

onMounted(() => {
  loadData()
  customerData()
})
</script>
<style scoped lang="scss">
.outerTable {
  .el-dropdown {
    margin-left: 10px;
  }

  .after-sale,
  .after-sale-deliver {
    color: #ffc000;
    margin-left: 5px;
  }

  .after-sale {
    font-size: 12px;
  }
}
</style>
